package middleware

import (
	"github.com/gin-gonic/gin"
	"gintify/core"
	"gintify/model"
	r "gintify/response"
	"net/http"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取authorization header
		tokenString := c.GetHeader("Authorization")
		if tokenString == "" {
			r.Response(c, http.StatusUnauthorized, 401, "未提供token", nil)
			c.Abort()
			return
		}
		token, claims, err := core.ParseToken(tokenString)
		if err != nil || !token.Valid {
			r.Response(c, http.StatusUnauthorized, 401, "非法Token", err)
			c.Abort()
			return
		}
		// 验证成功后获取UserId
		userId := claims.UserId
		var user model.SysUser
		core.DB.Debug().Preload("Role").First(&user, userId)

		// 用户不存在
		if user.ID == 0 {
			r.Response(c, http.StatusUnauthorized, 401, "用户不存在", nil)
			c.Abort()
			return
		}
		// 用户存在，将user信息写入上下文
		c.Set("user", user)
		c.Next()
	}
}
